<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            var numEnclaves = function (grid) {
                let m = grid.length
                let n = grid[0].length
                let sum = 0
                function dfs(i, j, isReset) {
                    if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == 0) return
                    if (!isReset) {
                        sum++
                    }
                    grid[i][j] = 0
                    dfs(i - 1, j, isReset)
                    dfs(i + 1, j, isReset)
                    dfs(i, j - 1, isReset)
                    dfs(i, j + 1, isReset)
                }
                for (let i = 0; i < m; i++) {
                    for (let j = 0; j < n; j++) {
                        if (i == 0 || j == 0 || i == m - 1 || j == n - 1) {
                            if (grid[i][j] == 1) {
                                dfs(i, j, true)
                            }
                        }
                    }
                }
                for (let i = 0; i < m; i++) {
                    for (let j = 0; j < n; j++) {
                        if (grid[i][j] == 1) {
                            dfs(i, j, false)
                        }
                    }
                }
                return sum
            }
        </script>
    </body>
</html>
